<?php 
/**
 * @version $Id$
 * @package
 * @author Alexander Anokhin <ava@vaz.ru>
 */
ini_set('session.save_path', '/tmp');
include_once('appBootstrap.php');

$pthRoot = dirname(__FILE__);

class Kpl_Controller_Router_Cli extends Zend_Controller_Router_Abstract implements Zend_Controller_Router_Interface {  
     public function assemble($userParams, $name = null, $reset = false, $encode = true) { }  
     public function route(Zend_Controller_Request_Abstract $dispatcher) {}  
}

include_once('appBootstrap.php');

try {
	$opts = new Zend_Console_Getopt(
	array(
  		'help|h' => 'Displays usage information.',  
		'username|u=s' => 'User for login.',
		'password|p=s' => 'Password to use when connecting to application.',
		'group|g=s' => 'Current user group',
  		'action|a=s' => 'Action to perform in format of controller.action',
		'args=s' => 'Additional agruments passed to action'  
		)
	);
	$opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
	exit($e->getMessage() ."\n\n". $e->getUsageMessage());
}

if(isset($opts->h)) {
	echo $opts->getUsageMessage();
	exit;
}

if(isset($opts->a)) {
	
	$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_NonPersistent);
	$authAdapter = Zend_Controller_Action_HelperBroker::getStaticHelper('AuthAdapterFactory')->getAuthAdapter();
	$authAdapter->setUsername($opts->u);
	$authAdapter->setPassword($opts->p);
	$authResult = Zend_Auth::getInstance()->authenticate($authAdapter);
	$reqRoute = array_reverse(explode('.',$opts->a));
	
	@list($action,$controller) = $reqRoute;
	parse_str(str_replace(',','&',$opts->args), $params);
	
	$request = new Zend_Controller_Request_Simple($action,$controller,'default', $params);

	$frontController->setRequest($request);
	$frontController->setRouter(new Kpl_Controller_Router_Cli());
	$frontController->setResponse(new Zend_Controller_Response_Cli());
	$frontController->throwExceptions(true);
	try {
		$frontController->dispatch();
	} catch(Exception $e) {
		echo "\n Error:",$e->getMessage(), "\n";	
	}
}